/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.hamacekj.dotaznikserver;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

/**
 * Zobrazí nastavení aplikace.
 * @author Jan Hamáček
 */
public class PreferenceDialog extends JDialog{

    public PreferenceDialog() {
        setupDialog();
    }

    public PreferenceDialog(Dialog owner) {
        super(owner, true);
        setupDialog();
    }

    public PreferenceDialog(Frame owner) {
        super(owner, true);
        setupDialog();
    }

    public PreferenceDialog(Dialog owner, String title) {
        super(owner, title, true);
        setupDialog();
    }

    public PreferenceDialog(Frame owner, String title) {
        super(owner, title, true);
        setupDialog();
    }
    
    /**
     * Vrací hodnotu, jestli tento dialog způsobil změnu nastavení aplikace.
     * @return true, pokud způsobil změnu nastavení.
     */
    public boolean preferenceChanged(){
        return this.preferenceChanged;
    }
    
    /**
     * Vrací hodnotu, jestli tento dialog nastavil nastavení ComputerList na nový,
     * existující soubor. Tj. jestli je potřeba znovu načíst seznam počítačů.
     * @return true, pokud dialog nastavil ComputerList na nový, existující soubor.
     */
    public boolean newComputerListSet(){
        return existingComputerListSet && preferenceChanged;
    }
    
    private void setupDialog(){
        Preferences pref = Preferences.userNodeForPackage(UI.class);
        this.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
        Container pane = this.getContentPane();
        JPanel buttons = new JPanel();
        buttons.setLayout(new GridBagLayout());
        JPanel content = new JPanel();
        content.setLayout(new GridBagLayout());
        JButton ok = new JButton("Ok");
        JButton cancel = new JButton("Zrušit");
        ok.addActionListener(new SubmitActionListener());
        cancel.addActionListener(new CancelActionListener());
        GridBagConstraints c = new GridBagConstraints();
        c.weightx = 1; c.anchor = GridBagConstraints.EAST;
        buttons.add(ok, c);
        c.weightx = 0; c.gridx = 1;
        buttons.add(cancel, c);
        c.gridx = 0; c.anchor = GridBagConstraints.WEST;
        content.add(new JLabel("Komunikační port:"), c);
        port = new JTextField();
        port.setText(new Integer(pref.getInt("Port", 7475)).toString());
        port.setPreferredSize(new Dimension(250, 25));
        c.gridx = 1; c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1;
        c.gridwidth = 2;
        content.add(port, c);
        c.gridx = 3; c.fill = GridBagConstraints.NONE; c.weightx = 0; c.gridwidth = 1;
        portError = new JLabel("");
        content.add(portError);
        c.gridx = 0; c.gridy = 1; c.weightx = 0;
        content.add(new JLabel("Soubor se seznamem uložených počítačů:"), c);
        c.gridx = 1; c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL;
        computersFile = new JTextField();
        computersFile.setText(pref.get("ComputersFile", "computers.list"));
        content.add(computersFile, c);
        c.gridx = 2; c.weightx = 0;
        JButton fireFileChooser = new JButton("...");
        fireFileChooser.addActionListener(new FireFileChooserActionListener());
        content.add(fireFileChooser, c);
        c.gridx = 3;
        computersFileError = new JLabel();
        content.add(computersFileError, c);
        pane.add(content, BorderLayout.CENTER);
        pane.add(buttons, BorderLayout.SOUTH);
        this.pack();
    }
    
    private class SubmitActionListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            String text = port.getText();
            try{
                int portInt = Integer.parseInt(text);
                Preferences pref = Preferences.userNodeForPackage(UI.class);
                if(portInt != pref.getInt("Port", 7475)){
                    preferenceChanged = true;
                }
                pref.putInt("Port", portInt);
                File f = new File(computersFile.getText());
                if(!f.exists()){
                    f.createNewFile();
                }else{
                    existingComputerListSet = true;
                }
                if(!f.canWrite()){
                    throw new IOException();
                }
                if(!pref.get("ComputersFile", "computers.list").equals(computersFile.getText())){
                    preferenceChanged = true;
                }
                pref.put("ComputersFile", computersFile.getText());
                pref.flush();
            }catch(NumberFormatException ex){
                portError.setText("<html><font color='red'>Musí být číslo</font></html>");
                return;
            }catch(BackingStoreException ex){
                JOptionPane.showMessageDialog(PreferenceDialog.this, "Nepodařilo se uložit data, změny nejsou aplikovány",
                        "Chyba při ukládání", JOptionPane.WARNING_MESSAGE);
                PreferenceDialog.this.setVisible(false);
            }
            catch(IOException ex){
                computersFileError.setText("Do tohoto souboru nemůžu zapisovat.");
            }
            PreferenceDialog.this.setVisible(false);
        }
    }
    
    private class CancelActionListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            PreferenceDialog.this.setVisible(false);
        }
        
    }
    
    private class FireFileChooserActionListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fch = new JFileChooser(computersFile.getText());
            fch.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            fch.setMultiSelectionEnabled(false);
            if(fch.showDialog(PreferenceDialog.this, "Vyber") == JFileChooser.APPROVE_OPTION){
                File f = fch.getSelectedFile();
                if(f.isDirectory()){
                    f = f.toPath().resolve("computers.list").toFile();
                }
                computersFile.setText(f.getPath());
            }
        }
    }
    
    private JTextField port;
    private JLabel portError;
    private JTextField computersFile;
    private JLabel computersFileError;
    private boolean preferenceChanged = false;
    private boolean existingComputerListSet = false;
}
